<template>
  <div class="user-list">
    <!-- 过滤卡片 -->
    <el-card class="filter-card">
      <el-form :inline="true" :model="filterForm" class="demo-form-inline">
        <el-form-item label="电话号码">
          <el-input
              v-model="filterForm.phone"
              placeholder="请输入电话号码"
              clearable
          ></el-input>
        </el-form-item>
        <el-form-item label="用户状态">
          <el-select
              v-model="filterForm.status"
              placeholder="请选择状态"
              clearable
              style="width: 150px"
          >
            <el-option label="全部" value=""></el-option>
            <el-option label="正常" :value="1"></el-option>
            <el-option label="封禁" :value="0"></el-option>
          </el-select>
        </el-form-item>
        <el-form-item>
          <el-button type="primary" @click="searchUsers" :loading="loading">
            <i class="el-icon-search"></i> 查询
          </el-button>
          <el-button @click="resetFilter">
            <i class="el-icon-refresh"></i> 重置
          </el-button>
        </el-form-item>
      </el-form>
    </el-card>

    <!-- 用户列表卡片 -->
    <el-card>
      <div slot="header" class="clearfix">
        <span>用户列表</span>
        <el-button
            style="float: right; margin-top: -5px"
            type="primary"
            @click="handleAdd"
        >
          <i class="el-icon-plus"></i> 添加用户
        </el-button>
      </div>

      <!-- 用户表格 -->
      <el-table
          :data="userList"
          stripe
          border
          fit
          highlight-current-row
          v-loading="loading"
      >
        <el-table-column prop="userId" label="用户ID" width="100"></el-table-column>
        <el-table-column prop="username" label="用户名" width="120"></el-table-column>
        <el-table-column prop="email" label="邮箱"></el-table-column>
        <el-table-column prop="phone" label="手机号"></el-table-column>
        <el-table-column label="性别" prop="genderDesc"></el-table-column>
        <el-table-column label="角色" prop="roleDesc"></el-table-column>
        <el-table-column prop="createTime" label="注册时间" width="180">
          <template #default="{ row }">
            {{ formatDate(row.createTime) }}
          </template>
        </el-table-column>
        <el-table-column prop="status" label="状态">
          <template #default="{ row }">
            <el-tooltip :content="row.status === 1 ? '正常' : '封禁'" placement="top">
              <el-switch
                  v-model="row.status"
                  active-color="#13ce66"
                  inactive-color="#ff4949"
                  :active-value="1"
                  :inactive-value="0"
                  :disabled="!canChangeStatus(row)"
                  @change="newStatus => handleSwitchChange(row, newStatus)">
              </el-switch>
            </el-tooltip>
          </template>
        </el-table-column>
        <el-table-column label="操作" width="200" align="center">
          <template #default="{ row }">
            <el-link type="primary" @click="handleView(row)">查看</el-link>
            <el-divider direction="vertical" />
            <el-link type="danger" @click="handleDelete(row)">删除</el-link>
            <el-divider direction="vertical" />
            <el-link type="success" @click="handleEdit(row)">编辑</el-link>
          </template>
        </el-table-column>
      </el-table>

      <!-- 分页 -->
      <el-pagination
          @size-change="handleSizeChange"
          @current-change="handleCurrentChange"
          :current-page="currentPage"
          :page-sizes="[5, 10, 20, 50]"
          :page-size="pageSize"
          layout="total, sizes, prev, pager, next, jumper"
          :total="total"
          class="pagination-container"
      ></el-pagination>
    </el-card>

    <!-- 用户详情/编辑弹窗 -->
    <el-dialog
        v-model="dialogVisible"
        :title="dialogTitle"
        width="600px"
        :close-on-click-modal="false"
        @closed="resetForm"
    >
      <el-form
          ref="userForm"
          :model="userInfo"
          :rules="userRules"
          label-width="120px"
      >
        <!-- 个人详情 -->
        <el-form-item label="用户名" prop="username">
          <el-input
              v-model="userInfo.username"
              :disabled="isViewMode"
              placeholder="请输入用户名"
          ></el-input>
        </el-form-item>

        <el-form-item label="邮箱" prop="email">
          <el-input
              v-model="userInfo.email"
              :disabled="isViewMode"
              placeholder="请输入邮箱"
          ></el-input>
        </el-form-item>

        <el-form-item label="手机号" prop="phone">
          <el-input
              v-model="userInfo.phone"
              :disabled="isViewMode"
              placeholder="请输入手机号"
          ></el-input>
        </el-form-item>

        <el-form-item label="个人简介">
          <el-input
              type="textarea"
              v-model="userInfo.bio"
              :disabled="isViewMode"
              :rows="3"
              placeholder="请输入个人简介"
          ></el-input>
        </el-form-item>

        <el-form-item label="性别" v-if="isViewMode">
          <el-input
              v-model="userInfo.genderDesc"
              disabled
          ></el-input>
        </el-form-item>

        <el-form-item label="角色">
          <el-input
              v-if="isViewMode"
              v-model="userInfo.roleDesc"
              disabled
          ></el-input>
          <el-select
              v-else
              v-model="userInfo.roleCode"
              placeholder="请选择角色"
              clearable
              style="width: 100%"
              :disabled="!canEditRole(userInfo)"
          >
            <el-option label="普通用户" value="1"></el-option>
            <el-option label="管理员" value="2"></el-option>
            <!-- <el-option label="编辑" value="3"></el-option> -->
            <el-option label="公关部门" value="4"></el-option>
            <el-option label="人事部门" value="5"></el-option>
            <el-option label="会计部门" value="6"></el-option>
          </el-select>
        </el-form-item>

        <el-form-item label="状态" v-if="!isViewMode">
          <el-radio-group v-model="userInfo.status" :disabled="!canChangeStatus(userInfo)">
            <el-radio :label="0">封禁</el-radio>
            <el-radio :label="1">正常</el-radio>
          </el-radio-group>
        </el-form-item>
        <el-form-item label="状态" v-else>
          <el-tag :type="userInfo.status === 1 ? 'success' : 'danger'">
            {{ userInfo.status === 1 ? '正常' : '封禁' }}
          </el-tag>
        </el-form-item>

        <!-- 时间信息 -->
        <el-form-item label="注册时间">
          <el-input v-model="formattedCreateTime" disabled></el-input>
        </el-form-item>

        <el-form-item label="最后登录时间">
          <el-input v-model="formattedLastLoginTime" disabled></el-input>
        </el-form-item>
      </el-form>

      <template #footer>
        <el-button
            v-if="!isViewMode"
            type="primary"
            @click="saveUser"
            :loading="saving"
        >
          保存
        </el-button>
        <el-button @click="dialogVisible = false">
          {{ isViewMode ? '关闭' : '取消' }}
        </el-button>
      </template>
    </el-dialog>
  </div>
</template>

<script>
import axios from '@/utils/request';

export default {
  name: 'UserList',
  data() {
    // 手机号验证规则
    const validatePhone = (rule, value, callback) => {
      if (!value) {
        return callback(new Error('请输入手机号'));
      }
      const reg = /^1[3-9]\d{9}$/;
      if (!reg.test(value)) {
        callback(new Error('请输入有效的11位手机号'));
      } else {
        callback();
      }
    };

    return {
      loading: true,
      saving: false,
      filterForm: {
        phone: '',
        status: ''
      },
      userList: [],
      currentPage: 1,
      pageSize: 5,
      total: 0,
      dialogVisible: false,
      isViewMode: false, // true=查看模式, false=编辑模式
      userInfo: {
        userId: '',
        username: '',
        email: '',
        phone: '',
        genderDesc: '',
        roleCode: '',
        status: 1,
        bio: '',
        roleDesc: '',
        createTime: '',
        lastLoginTime: ''
      },
      userRules: {
        username: [
          { required: true, message: '请输入用户名', trigger: 'blur' },
          { min: 2, max: 20, message: '用户名长度在 2 到 20 个字符', trigger: 'blur' }
        ],
        email: [
          { required: true, message: '请输入邮箱', trigger: 'blur' },
          { type: 'email', message: '请输入有效的邮箱地址', trigger: ['blur', 'change'] }
        ],
        phone: [
          { required: true, message: '请输入手机号', trigger: 'blur' },
          { validator: validatePhone, trigger: ['blur', 'change'] }
        ]
      }
    }
  },
  computed: {
    // 对话框标题
    dialogTitle() {
      return this.isViewMode ? '用户详情' : this.userInfo.userId ? '编辑用户' : '添加用户';
    },

    // 格式化的创建时间
    formattedCreateTime() {
      return this.formatDate(this.userInfo.createTime);
    },

    // 格式化的最后登录时间
    formattedLastLoginTime() {
      return this.formatDate(this.userInfo.lastLoginTime);
    }
  },
  mounted() {
    this.getUserList();
  },
  methods: {
    // 检查是否可以修改状态
    canChangeStatus(user) {
      const currentUserRole = localStorage.getItem('roleCode');
      const targetUserRole = user.roleCode;
      console.log({currentUserRole, targetUserRole});
      

      // 管理员不能修改超级管理员(roleCode=3)和同级管理员(roleCode=2)的状态
      if (currentUserRole === '2') { // 当前用户是管理员
        return targetUserRole !== 3 && targetUserRole !== 2; // 只能修改非管理员和非超级管理员
      }

      // 其他角色按需处理
      return true;
    },

    // 检查是否可以编辑角色
    canEditRole(user) {
      const currentUserRole = localStorage.getItem('roleCode');
      const targetUserRole = user.roleCode;

      // 管理员不能编辑超级管理员(roleCode=3)和同级管理员(roleCode=2)的角色
      if (currentUserRole === '2') { // 当前用户是管理员
        return targetUserRole !== '3' && targetUserRole !== '2'; // 只能编辑非管理员和非超级管理员
      }

      // 其他角色按需处理
      return true;
    },

    // 获取用户列表
    getUserList() {
      this.loading = false;
      axios.get('/user/page', {
          params: {
            phone: this.filterForm.phone,
            status: this.filterForm.status,
            current: this.currentPage,
            size: this.pageSize
          }
        }).then(response =>{
          if (response.data.code === 200) {
            this.userList = response.data.data.records;
            this.total = response.data.data.total;
          } else {
            this.$message.error(response.data.message || '获取用户列表失败');
          }
        })
    },

    // 搜索用户
    searchUsers() {
      this.currentPage = 1;
      this.getUserList();
    },

    // 重置过滤条件
    resetFilter() {
      this.filterForm = {
        phone: '',
        status: ''
      };
      this.currentPage = 1;
      this.getUserList();
    },

    // 处理分页大小变化
    handleSizeChange(size) {
      this.pageSize = size;
      this.currentPage = 1;
      this.getUserList();
    },

    // 处理当前页变化
    handleCurrentChange(page) {
      this.currentPage = page;
      this.getUserList();
    },

    // 格式化日期
    formatDate(dateStr) {
      if (!dateStr) return '';
      const date = new Date(dateStr);
      return date.toLocaleString();
    },

    // 处理添加用户
    handleAdd() {
      this.$router.push('/userAdd');
    },

    // 查看用户详情
    handleView(row) {
      this.userInfo = { ...row };
      this.isViewMode = true;
      this.dialogVisible = true;
    },

    // 编辑用户
    handleEdit(row) {
      this.userInfo = { ...row };
      this.isViewMode = false;
      this.dialogVisible = true;
    },

    // 重置表单
    resetForm() {
      if (this.$refs.userForm) {
        this.$refs.userForm.resetFields();
      }
    },

    // 保存用户信息
    async saveUser() {
      try {
        // 验证表单
        const valid = await this.$refs.userForm.validate();
        if (!valid) return;

        this.saving = true;

        // 发送请求
        axios.post('/user/saveOrUpdate', this.userInfo,)
         .then(response =>{
          if (response.data.code === 200) {
            this.$message.success(this.userInfo.userId ? '用户修改成功' : '用户添加成功');
            this.dialogVisible = false;
            // 刷新用户列表
            this.getUserList();
          } else {
            this.$message.error(response.data.message || '操作失败，请重试');
          }
        })
      } catch (error) {
        console.error('保存用户失败:', error);
        const errorMsg = error.response?.data?.message || '保存用户失败，请检查网络连接';
        this.$message.error(errorMsg);
      } finally {
        this.saving = false;
      }
    },

    // 删除用户
    handleDelete(row) {
      this.$confirm(`确定要删除该用户吗?`, '删除确认', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      }).then(resp => {
        try {
          axios.delete(`/user/delete`, {
            params:{
              userId:row.userId
            }
          }).then(response => {
            if (response.data.code === 200) {
              this.$message.success('用户删除成功');
              this.handleCurrentChange(this.currentPage);
            } else {
              this.$message.error(response.data.message || '删除用户失败');
            }
          })
        } catch (error) {
          console.error('删除用户失败:', error);
          this.$message.error('删除用户失败，请检查网络连接');
        }
      }).catch(() => {
        this.$message.info('已取消删除');
      });
    },

    // 状态切换处理函数
    handleSwitchChange(user, newStatus) {
      // 检查权限
      if (!this.canChangeStatus(user)) {
        this.$message.warning('您无权修改该用户的状态');
        user.status = user.status === 1 ? 0 : 1; // 恢复原状态
        return;
      }

      const action = newStatus === 0 ? '禁用' : '启用';
      const statusText = newStatus === 0 ? '禁用' : '正常';

      this.$confirm(`确定要${action}用户 "${user.username}" 吗?`, '操作确认', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      }).then(() => {
        axios.post(`/user/updateStatus?userId=${user.userId}&status=${user.status}`).then(response => {
          if (response.data.code == 200) {
            this.$message.success(`用户状态已更新为: ${statusText}`);
          } else {
            user.status = user.status === 1 ? 0 : 1;
            this.$message.error('状态更新失败: ' + response.data.message);
          }
        }).catch(error => {
          user.status = user.status === 1 ? 0 : 1;
          this.$message.error('请求失败: ' + error.message);
        });
      }).catch(() => {
        user.status = user.status === 1 ? 0 : 1;
        this.$message.info('操作已取消');
      });
    }
  }
}
</script>

<style scoped>
.user-list {
  padding: 20px;
}

.filter-card {
  margin-bottom: 20px;
}

.pagination-container {
  margin-top: 20px;
  text-align: right;
}

.clearfix:after {
  content: "";
  display: table;
  clear: both;
}
</style>